<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { listBooksService, updateBookService } from "@/api/books.js";
import useUserStore from "@/stores/userStore.js";
import { addBorrowService } from "@/api/borrowing.js";

const selectedBooks = ref([]);
const booksData = ref([]);
const pageNum = ref(1);
const pageSize = ref(15);
const total = ref(10);

const userStore = useUserStore();
const currentUser = userStore.info;

const searchBook = ref({
  bookId: "",
  bookName: "",
  description: "",
  price: "",
  language: "",
  isbn: "",
  status: "",
});

const handleSizeChange = (size) => {
  pageSize.value = size;
  listBooks();
};

const handleCurrentChange = (num) => {
  pageNum.value = num;
  listBooks();
};

const handleSelectionChange = (selection) => {
  selectedBooks.value = selection;
};

const listBooks = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchBook.value,
  };
  let result = await listBooksService(params);
  total.value = result.data.total;
  booksData.value = result.data.records;
};

const reset = async () => {
  searchBook.value.bookId = "";
  searchBook.value.bookName = "";
  searchBook.value.description = "";
  searchBook.value.price = "";
  searchBook.value.language = "";
  searchBook.value.isbn = "";
  searchBook.value.status = "";
  await listBooks();
};

const statusCellStyle = ({ row, column }) => {
  if (column.property === "status") {
    switch (row.status) {
      case "未借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(133, 206, 97, 0.3)" };
      case "已借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(247, 137, 137, 0.3)" };
      default:
        // 设置为50%透明度
        return { backgroundColor: "rgba(235, 181, 99, 0.3)" };
    }
  }
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "";
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}:${month}:${day}-${hours}:${minutes}:${seconds}`;
};

const borrowingthisBook = async (book) => {
  try {
    await ElMessageBox.confirm(
      `确定要借阅书籍《${book.bookName}》吗？`,
      "确认借阅",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );
    const newBorrow = {
      bookId: book.bookId,
      userId: currentUser.userId,
    };
    let result = await addBorrowService(newBorrow);
    if (result.code === 0) {
      // 更新图书状态为 "已借阅"
      const updatedBook = { ...book, status: "已借阅" };
      await updateBookService(updatedBook);
      ElMessage.success("借阅成功");
      await listBooks();
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("借阅失败");
      console.error(error);
    }
  }
};

const bulkBorrowBooks = async () => {
  try {
    await ElMessageBox.confirm(`确定要借阅选中的书籍吗？`, "确认批量借阅", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    let successCount = 0;
    let skipCount = 0;

    for (const book of selectedBooks.value) {
      if (book.status === "未借阅") {
        const newBorrow = {
          bookId: book.bookId,
          userId: currentUser.userId,
        };
        let result = await addBorrowService(newBorrow);
        if (result.code === 0) {
          const updatedBook = { ...book, status: "已借阅" };
          await updateBookService(updatedBook);
          successCount++;
        } else {
          ElMessage.error(
            `借阅书籍《${book.bookName}》失败: ${result.message}`,
          );
        }
      } else {
        skipCount++;
      }
    }

    ElMessage.success(
      `批量借阅完成，成功借阅 ${successCount} 本书，跳过 ${skipCount} 本书`,
    );
    await listBooks();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量借阅失败");
      console.error(error);
    }
  }
};

listBooks();
</script>

<template>
  <div class="search-container">
    <el-input
      v-model="searchBook.bookId"
      placeholder="请输入书籍ID"
      clearable
      class="search-input"
      type="number"
      :min="1"
    />
    <el-input
      v-model="searchBook.bookName"
      placeholder="请输入书籍名称"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.description"
      placeholder="请输入书籍描述"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.price"
      placeholder="请输入书籍价格"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.language"
      placeholder="请输入书籍语言"
      clearable
      class="search-input"
    />
    <el-input
      v-model="searchBook.isbn"
      placeholder="请输入书籍ISBN"
      clearable
      class="search-input"
      type="number"
      :min="0"
    />
    <el-input
      v-model="searchBook.status"
      placeholder="请输入书籍状态"
      clearable
      class="search-input"
    />
  </div>
  <div class="button-group">
    <div class="extra-buttons">
      <el-button @click="bulkBorrowBooks" type="primary" icon="Refresh"
        >批量借阅
      </el-button>
    </div>
    <el-button @click="listBooks" type="primary" icon="Search">搜索</el-button>
    <el-button @click="reset" type="warning" icon="RefreshRight"
      >重置
    </el-button>
  </div>

  <el-table
    :data="booksData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column fixed sortable prop="bookId" label="图书ID" />
    <el-table-column sortable prop="bookName" label="书名" />
    <el-table-column sortable prop="description" label="描述" />
    <el-table-column sortable prop="price" label="价格" />
    <el-table-column
      sortable
      prop="language"
      label="语言"
      :filters="[
        { text: '中文', value: '中文' },
        { text: '外文', value: '外文' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column sortable prop="isbn" label="ISBN" />
    <el-table-column
      sortable
      prop="shelfTime"
      label="上架时间"
      :formatter="formatDate"
    />
    <el-table-column
      sortable
      prop="status"
      label="状态"
      :filters="[
        { text: '已借阅', value: '已借阅' },
        { text: '未借阅', value: '未借阅' },
        { text: '丢失', value: '丢失' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column label="操作" align="center" fixed="right" width="120">
      <template #default="scope">
        <el-button
          v-if="scope.row.status === '未借阅'"
          type="primary"
          @click="borrowingthisBook(scope.row)"
          icon="Memo"
          >借阅
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageNum"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30, 50, 100]"
    background
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    style="margin-top: 20px; justify-content: flex-end"
  />
</template>

<style scoped></style>
